import { Toast } from '@nutui/nutui-react';
import { AxiosResponse } from 'axios';

import Storage from '@/application/utils/storage';

const HttpErrorList: Record<number, string> = {
  404: '请求地址错误或后端接口未部署',
  403: '没有相关权限',
  401: '登录状态过期, 需要重新登录',
  500: '后端服务有未处理的错误',
  502: '后端接口无响应',
  504: '请求超时, 可能是网络问题, 请稍后重试'
};

export class HttpBizError extends Error {
  request: unknown;

  response: unknown;

  constructor(message: string, request: unknown, response: unknown) {
    super(message);
    this.name = 'HttpBizError';
    this.request = request;
    this.response = response;
  }
}

export class HttpNetworkError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'HttpNetworkError';
  }
}

export type StandardResponse<T = unknown> = {
  code?: number;
  success?: boolean;
  message?: string;
  info?: string;
  result: T;
};

function Catcher<T>(
  response: AxiosResponse<StandardResponse<T>>,
  isHttpError: boolean,
  noGlobalMessage?: boolean
): void {
  if (isHttpError) {
    const { status } = response;
    const baseMessage = '网络请求错误';
    if (!noGlobalMessage) {
      Toast.show({
        title: HttpErrorList[status],
        icon: 'null',
        lockScroll: true
      });
    }
    throw new HttpNetworkError(baseMessage);
  } else {
    const { data } = response;
    const baseMessage = data?.info || data?.message || '未知错误信息';
    // if (data?.code === 403) {
    //   Storage.login.set(null);
    // }

    if (data?.code === 12000) {
      window.location.href = '/error';
      return;
    }

    console.log('noGlobalMessage', noGlobalMessage, data);

    if (!noGlobalMessage) {
      Toast.show({
        title: baseMessage,
        icon: 'null',
        lockScroll: true
      });
    }
    throw new HttpBizError(baseMessage, response.request, data);
  }
}
export default Catcher;
